<script setup lang="ts">

import { ref, onMounted } from 'vue'

const task = ref([''])
const val = ref('')


function addTask() {
    task.value.push(val.value)
    sessionStorage.setItem('task', JSON.stringify(task.value))
    console.log(task.value)
}

function delTask(event: Event) {
    const target = event.target as HTMLElement | null;
    if (target !== null) {
        const son = target.parentNode?.parentNode?.parentNode as HTMLElement | undefined;
        if (son && son.parentNode) {
            const children = Array.from(son.parentNode.children as HTMLCollection);
            const index = children.indexOf(son);

            task.value.splice(index + 1, 1)
            sessionStorage.setItem('task', JSON.stringify(task.value))
        }
    }
}

function changeTask(event: Event) {
    const target = event.target as HTMLElement | null;
    if (target !== null) {
        const son = target.parentNode?.parentNode?.parentNode as HTMLElement | undefined;
        if (son && son.parentElement) {
            const children = Array.from(son.parentElement.children as HTMLCollection);
            const index = children.indexOf(son);
            const newTask = prompt('请输入新的任务内容')
            if (newTask !== null) {
                task.value[index + 1] = newTask
            }
            sessionStorage.setItem('task', JSON.stringify(task.value))
        }
    }
}

onMounted(() => {
    const tasks = sessionStorage.getItem('task')
    if (tasks !== null) {
        task.value = JSON.parse(tasks)
    }
})

// 添加 defineExpose 来暴露 task
defineExpose({ task })

</script>

<template>
    <div class="container"
        style="display: flex;flex-direction: column;box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);padding: 20px;border-radius: 10px;position: relative;;left: 45%;top:150px">
        <div style="width: 300px; display: flex;">
            <input id="save" type="text" v-model.trim="val" placeholder="please input task"
                style="width: 200px;height: 30px;">
            <button id="add" @click="addTask()">click</button>
        </div>
        <div style="height: 250px;overflow: auto;">

            <div id="list-box" style="width: 300px;">
                <div v-for="item in task.slice(1)">
                    <div style="width: 200px;height: 30px;display: flex;justify-content: space-between;">
                        <div style="max-width: 50px; overflow-x: auto;"> {{ item }}</div>
                        <div>
                            <button id="change" @click="changeTask($event)">change</button>
                            <button id="del" @click="delTask($event)">delete</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>



</template>